package com.tensquare.article.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
@CrossOrigin //解决跨域
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    //GET  /article 文章全部列表
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
       List<Article> list=articleService.finfAll();
       return new Result(true,"查询成功", StatusCode.OK,list);
    }

    //GET  /article/{articleId} 根据ID查询文章
    @GetMapping("/{articleId}")
    public Result findById(@PathVariable String articleId){
        Article article=articleService.findById(articleId);
        return new Result(true,"查询成功",StatusCode.OK,article);
    }

    //POST /article  增加文章
    //使用RequestBody 来自动封装对象
    @PostMapping
    public Result save(@RequestBody Article article){
        articleService.save(article);
        return new Result(true,"添加成功",StatusCode.OK);
    }

    //PUT /article/{articleId}  修改文章
    //id在请求头中 内容在请求体中
    @PutMapping("/{articleId}")
    public Result updateById(@PathVariable String articleId,@RequestBody Article article){
        //设置id
        article.setId(articleId);
        articleService.updateById(article);
        return new Result(true,"修改成功",StatusCode.OK);

    }


    //DELETE /article/{articleId} 根据ID删除文章
    @DeleteMapping("/{articleId}")
    public Result deleteById(@PathVariable String articleId){
        articleService.deleteById(articleId);
        return new Result(true,"删除成功",StatusCode.OK);
    }

    //POST  /article/search 根据条件查询文章列表


   // POST /article/search/{page}/{size} 文章分页
    //使用map接受 请求体数据 方便变量
    @PostMapping("/search/{page}/{size}")
    public Result findByPage(@PathVariable Integer page,@PathVariable Integer size,
                             @RequestBody Map<String,Object> map){

        Page<Article> pageData=articleService.findByPage(page,size,map);

        return new Result(true,"查询成功",StatusCode.OK,new PageResult<Article>(pageData.getTotal(),pageData.getRecords()));
    }

}
